package com.walter.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.walter.Application;
import com.walter.common.PageVO;
import com.walter.entity.Dict;
import com.walter.exception.LogicException;
import com.walter.mapper.DictMapper;
import com.walter.model.form.SaveDictForm;
import com.walter.model.query.DictQuery;
import com.walter.util.Kv;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author ：ch
 * @date ：Created in 2021/5/25
 * @description：
 * @modified By：
 * @version: 1.0
 */
@Service
@Slf4j
public class DictService {
    @Autowired
    private DictMapper dictMapper;

    //分页查询字典量
    public PageVO<Dict> find(DictQuery query){
        return Optional.of(query)
                .map(q -> new Page<Dict>(q.getPage().getPageNum(),q.getPage().getPageSize()))
                .map(p -> new PageVO<>(p.setRecords(dictMapper.find(p, BeanUtil.beanToMap(query)))))
                .get();
    }

    //查询所有一级字典量(分页查询的条件、保存时所属父级字典)
    public List<cn.hutool.core.lang.Dict> findAllFirstLevelDict(){
        List<Dict> list = dictMapper.selectList(new EntityWrapper<Dict>().isNull("pid"));
        return list.stream().map(dict ->
                cn.hutool.core.lang.Dict.create().set("id",dict.getId()).set("name",dict.getName())
        ).collect(Collectors.toList());
    }

    //添加/修改字典量
    @Transactional
    public Integer save(SaveDictForm form){
        Integer retVal = 0,dictId = form.getId();
        String code = form.getCode();
        Dict dict;
        if (null == dictId){
            if (null != dictMapper.findByCode(code)){
                log.error("dict's code can not repeat");
                throw new LogicException("字典量的英文名称不能重复");
            }
            dict = new Dict().setCreateTime(new Date());
            BeanUtil.copyProperties(form,dict);
            retVal += dictMapper.insert(dict);
        }
        else {
            if (null != dictMapper.findByCodeAndId(code,dictId)){
                log.error("dict's code can not repeat");
                throw new LogicException("字典量的英文名称不能重复");
            }
            dict = dictMapper.selectById(dictId).setUpdateTime(new Date());
            if ( ! code.equals(dict.getCode())){
                log.error("dict's code can not update");
                throw new LogicException("字典量的英文名称不允许修改");
            }
            BeanUtil.copyProperties(form,dict);
            retVal += dictMapper.updateById(dict);
        }
        //更新系统缓存
        this.setSystemDictCache();
        return retVal;
    }

    public void setSystemDictCache(){
        List<Dict> secondLevelDictList = new ArrayList<>();
        secondLevelDictList = dictMapper.selectList(
                new EntityWrapper<Dict>().isNotNull("pid").and().ne("pid","")
        );
        secondLevelDictList.stream().forEach(dict -> Application.secondLevelDictMap.set(dict.getCode(),dict.getName()));
        List<Dict> firstLevelDictList = dictMapper.selectList(new EntityWrapper<Dict>().isNull("pid"));
        int length = firstLevelDictList.size();
        List<cn.hutool.core.lang.Dict> list = new ArrayList<>();
        Dict dict;
        for (int i = 0;i < length;i++){
            dict = firstLevelDictList.get(i);
            secondLevelDictList = dictMapper.selectByMap(Kv.by("pid",dict.getId()));
            list = secondLevelDictList.stream().map(dict1 ->
                    new cn.hutool.core.lang.Dict().set("code",dict1.getCode()).set("name",dict1.getName()))
                    .collect(Collectors.toList());
            Application.secondLevelDictByFirst.put(dict.getCode(),list);
        }
        log.info("secondLevelDictMap is {}",Application.secondLevelDictMap);
        log.info("secondLevelDictByFirst is {}", JSONUtil.parse(Application.secondLevelDictByFirst).toStringPretty());
    }

    // 查询单个详情
    public Dict findDetail(Integer dictId) {
        if (null == dictId){
            log.info("dictId is null");
            throw new LogicException("字典id为空");
        }
        Dict dict = dictMapper.selectById(dictId);
        if (null == dict){
            log.info("dict is null");
            throw new LogicException("id为" + dictId + "的字典数据不存在");
        }
        return dict;
    }
}
